import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_app/components/song_card.dart';
import 'package:flutter_app/model/song_model.dart';
import 'package:flutter_app/services/song_service.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

class SongPage extends StatefulWidget {
  SongPage({Key key}) : super(key: key);

  @override
  _SongPageState createState() => _SongPageState();
}

class _SongPageState extends State<SongPage> with AutomaticKeepAliveClientMixin{
  EasyRefreshController _controller;

  // 独立的滚动视图 防止tab切换时触发下拉刷新
  ScrollController _scrollController;
  List<SongItem> _songList = SongList([]).list;
  int page = 1;
  int limit = 10;
  bool hasMore = true;
  bool loading = true;
  bool error = false;
  String errorMsg = '';

  @override
  void initState() {
    super.initState();
    _controller = EasyRefreshController();
    _scrollController = ScrollController();
    _getSongs();
  }

  @override
  void dispose() {
    _controller.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  Future _getSongs({bool push = true}) async {
    try {
      //获取数据
//      Map<String, dynamic> result =
//          await SongService().getSongs(page: page, limit: limit);
      Map<String, dynamic> result;
      String data = await rootBundle.loadString("assets/data/song.json");
      result = jsonDecode(data);
      //将数据转为实体类
      SongList songListModel = SongList.fromJson(result['data']);
      setState(() {
        hasMore = page * limit < result['total'];
        page++;
        if (push) {
          _songList = songListModel.list;
        } else {
          _songList.addAll(songListModel.list);
        }
      });
    } catch (e) {
      setState(() {
        error = true;
        errorMsg = e.toString();
      });
    } finally {
      setState(() {
        loading = false;
      });
    }
  }

  //上拉加载
  Future _onRefresh() async {
    if (error) {
      setState(() => error = false);
    }
    page = 1;
    await _getSongs();
    _controller.resetLoadState();
  }

  //下拉刷新
  Future _onLoad() async {
    print('加载更多');
    if (hasMore) {
      await _getSongs(push: false);
    }
    _controller.finishLoad(noMore: !hasMore);
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return EasyRefresh(
      // 开启首次加载刷新
      firstRefresh: true,
      // 加载时的loading
      // 空视图、异常视图

      enableControlFinishRefresh: false,
      enableControlFinishLoad: true,
      controller: _controller,
      header: ClassicalHeader(),
      footer: ClassicalFooter(),
      onRefresh: _onRefresh,
      onLoad: _onLoad,
      child: ListView.builder(
          controller: _scrollController,
          itemCount: _songList.length,
          itemBuilder: (BuildContext context, int index) {
            return Column(
              children: [
                SizedBox(height: 10),
                SongCard(songItem: _songList[index]),
              ],
            );
          }),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
